package com.example.demo.service.Impl;

import com.example.demo.domain.User;
import com.example.demo.repository.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author WaterTiger
 * @see com.example.demo.service.UserService
 * @see com.example.demo.utils.UserUtil
 * @since 2020/6
 */
@Service
public class UserServiceImpl implements UserService {
    private static UserUtil userUtil = new UserUtil();
    {
        userUtil.init();
    }

    @Autowired
    private UserMapper userMapper;
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void addUser(User user) {
        userMapper.addUser(
                user.getUsername(),
                user.getPwd(),
                user.getIconURL(),
                user.getPhone(),
                user.getAddress(),
                user.getState(),
                user.getTimes()
                );
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void delUser(int id) {
        userMapper.delUserById(id);
        userUtil.deleteCache(id);
    }


    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public User getUserById(int id) {
        User user = userUtil.getCache(id);
        if(user == null){
            user = userMapper.getUserById(id);
        }
        userUtil.updateCount(user);
        return user;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public List<User> getAll() {
        return null;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void saveUser(User user) {
        int id = user.getId();
        userMapper.saveUser(
                user.getId(),
                user.getUsername(),
                user.getPwd(),
                user.getIconURL(),
                user.getPhone(),
                user.getAddress(),
                user.getState(),
                user.getTimes()
        );
        userUtil.updateCache(user);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public boolean CheckPassword(String username,String password)
    {
        return userMapper.CheckPassword(username, password)==null?false:true;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public User getUserByUserName(String username)
    {
        return userMapper.getUserByUserName(username);
    }
}
